new Vue({
    el: '#content',
    data: {
        adminUsers: [],
        adminUser: {
            adminId: "",
            username: "",
            password: "",
            role: "",
            createdAt: "",
            updatedAt: ""
        }
    },
    created: function () {
        axios.get("http://localhost:8080/AdminUser/all").then(response => {
            this.adminUsers = response.data.data; // 直接使用 this
        }).finally(() => {
            this.initDataTable(); // 确保在获取数据后调用 DataTable 初始化
        });
        $("span.mr-2.d-none.d-lg-inline.text-gray-600.small").text(localStorage.getItem("nickName"));
    },
    methods: {
        initDataTable() {
            // 使用 DataTable 初始化表格
            const table = $('#dataTable').DataTable({
                pageLength: 10, // 默认每页显示条数
                destroy: true // 允许重新初始化 DataTable
            });

            // 清空现有的数据
            table.clear();

            // 绑定点击事件
            $(document).ready(() => {
                $('#dataTable').on('click', '.update-btn', (e) => {
                    const adminId = $(e.currentTarget).data('whatever');
                    this.initUpdateAdminUser(adminId);
                });
                $('#dataTable').on('click', '.delete-btn', (e) => {
                    const adminId = $(e.currentTarget).data('whatever');
                    this.deleteAdminUser(adminId);
                });
            });
        },
        initUpdateAdminUser: function (adminId) {
            axios.get("http://localhost:8080/AdminUser/selectAdminUserById", {
                params: {
                    "adminId": adminId,
                }
            }).then(response => {
                this.adminUser = response.data.data;
            })
        },
        insertAdminUser() {
            axios.post("http://localhost:8080/AdminUser/insert", {
                username: this.adminUser.username,
                password: this.adminUser.password,
                role: this.adminUser.role
            }).then(response => {
                if (response.data.code === 200) {
                    alert(response.data.msg);
                    location.href = "admin-user.html";
                }
            })
        },
        updateAdminUser() {
            axios.post("http://localhost:8080/AdminUser/update", {
                adminId: this.adminUser.adminId,
                username: this.adminUser.username,
                password: this.adminUser.password,
                role: this.adminUser.role
            }).then(response => {
                if (response.data.code === 200) {
                    alert(response.data.msg);
                    location.href = "admin-user.html";
                }
            })
        },
        deleteAdminUser: function (adminId) {
            axios.get("http://localhost:8080/AdminUser/delete", {
                params: {
                    "adminId": adminId
                }
            }).then(response => {
                if (response.data.code === 200) {
                    alert(response.data.msg);
                    location.href = "admin-user.html";
                }
            })
        },
        convertToCSV: function (objArray) {
            const csvRows = [];
            // 获取表头
            const headers = Object.keys(objArray[0]);
            csvRows.push(headers.join(',')); // 将表头加入到 CSV 行

            // 将每个对象的值转换为 CSV 行
            for (const obj of objArray) {
                const values = headers.map(header => {
                    let value = obj[header];
                    // 如果值是对象或数组，转换为 JSON 字符串
                    if (typeof value === 'object' && value !== null) {
                        value = JSON.stringify(value);
                    }
                    // 处理特殊字符
                    const escaped = (value || '').toString().replace(/"/g, '""');
                    return `"${escaped}"`; // 用引号包裹值
                });
                csvRows.push(values.join(',')); // 将每行加入到 CSV 行
            }

            return '\uFEFF' + csvRows.join('\r\n'); // 添加 BOM 并使用 CRLF 换行符
        },
        exportCSV: function () {
            const csvData = this.convertToCSV(this.adminUsers);

            // 创建一个 Blob 对象，确保使用 UTF-8 编码
            const blob = new Blob([csvData], {type: 'text/csv;charset=utf-8;'});

            // 创建下载链接
            const link = document.createElement("a");
            if (window.navigator.msSaveOrOpenBlob) { // For IE
                window.navigator.msSaveBlob(blob, "adminUsers.csv");
            } else {
                const url = URL.createObjectURL(blob);
                link.href = url;
                link.setAttribute("download", "adminUsers.csv"); // 设置文件名
                document.body.appendChild(link);

                // 触发下载
                link.click();

                // 清理
                document.body.removeChild(link);
                URL.revokeObjectURL(url); // 释放内存
            }
        },
        exportExcel: function () {
            // 假设 this.transactions 是包含数据的数组
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.json_to_sheet(this.adminUsers);
            XLSX.utils.book_append_sheet(wb, ws, "adminUsers");

            // 使用 SheetJS 生成 Excel 文件
            const excelBuffer = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
            const blob = new Blob([excelBuffer], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});

            // 创建下载链接
            const link = document.createElement("a");
            if (window.navigator.msSaveOrOpenBlob) { // For IE
                window.navigator.msSaveBlob(blob, "adminUsers.xlsx");
            } else {
                const url = URL.createObjectURL(blob);
                link.href = url;
                link.setAttribute("download", "adminUsers.xlsx"); // 设置文件名
                document.body.appendChild(link);

                // 触发下载
                link.click();

                // 清理
                document.body.removeChild(link);
                URL.revokeObjectURL(url); // 释放内存
            }
        }
    },
    watch: {
        adminUsers(newValue) {
            // 当 transactions 发生变化时更新 DataTable
            this.$nextTick(() => {
                const table = $('#dataTable').DataTable();
                table.clear().rows.add(newValue.map(adminUser => [
                    adminUser.adminId,
                    adminUser.username,
                    adminUser.password,
                    adminUser.role,
                    adminUser.createdAt,
                    adminUser.updatedAt,
                    `<a href="#" class="btn btn-primary btn-icon-split update-btn"
                     data-toggle="modal" data-target="#UpdateModal"
                     data-whatever="${adminUser.adminId}">
                      <span class="text">修改</span>
                  </a>
                 <a href="#" class="btn btn-danger btn-icon-split delete-btn"
                 data-whatever="${adminUser.adminId}">
                     <span class="text">删除</span>
                 </a>`
                ])).draw();
            });
        }
    }
});